<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { CustomSearch } from '@/components/CustomSearch'
import { Table, TableColumn } from '@/components/Table'
import { ElMessageBox } from 'element-plus'
import { ref, reactive, onMounted, computed, watch, h, nextTick } from 'vue'
import { FormSchema } from '@/components/Form'
import { useSearch } from '@/hooks/web/useSearch'
import { useTable } from '@/hooks/web/useTable'
import { ElTag, ElMessage, ElUpload, ElButton, ElDialog, ElIcon } from 'element-plus'
import { BaseButton } from '@/components/Button'
import { useRouter } from 'vue-router'
import MarkdownIt from 'markdown-it'
import { Descriptions } from '@/components/Descriptions'
import {
  queryQtyChargArchInfo,
  importData,
  downloadTemplate as downloadTemplateApi,
  addAbnormalRecognition
} from '@/api/electricityAbnormal'
import { RECOGNITION_API } from '@/api/electricityApi'
import {
  sendMessageToDify,
  DifyRequest,
  DifyConfig,
  stopDifyConfig,
  stopDifyRequest,
  stopMessageToDify
} from '@/api/dify'
import { useUserStoreWithOut } from '@/store/modules/user'
import axios, { AxiosError } from 'axios'
import { custClsOptions, ecCategOptions, deregAttrTypeOptions, abnorCategEROptions } from '@/dicts'
import { size } from 'lodash-es'
import dayjs from 'dayjs'
import { DIFY_API_V1_URL, DIFY_API_KEY, DIFY_API_BASE_URL } from '@/constants/dify'

interface IResponse<T> {
  success?: boolean
  data?: T
  [key: string]: any
}

interface TableRow {
  abnorType?: string
  [key: string]: any
}

const { t } = useI18n()
const router = useRouter() // 获取router实例
// 搜索相关
const { searchRegister, searchMethods } = useSearch()
const searchRef = ref(null)
const { setSchema, getFormData, setValues } = searchMethods

// 多选相关数据
const selectedRows = ref<any[]>([])

// 获取上个月的起止日期（YYYYMM格式）
const getPreviousMonthRange = () => {
  const currentDate = dayjs()
  const previousMonth = currentDate.subtract(1, 'month')
  const previousMonthStr = previousMonth.format('YYYYMM')
  return [previousMonthStr, previousMonthStr]
}

// 处理多选变化
const handleSelectionChange = (selection: any[]) => {
  console.log('selection', selection)
  selectedRows.value = selection
  console.log('选中的行:', selection)
}
// 搜索表单配置
const schema = reactive<FormSchema[]>([
  {
    field: 'mgtOrgName',
    label: '管理单位',
    component: 'Input',
    componentProps: {
      placeholder: '请输入管理单位'
    }
  },
  {
    field: 'custNo',
    label: '用户编号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户编号'
    }
  },
  {
    field: 'expYm',
    label: '量费年月',
    component: 'DatePicker',
    componentProps: {
      type: 'monthrange',
      valueFormat: 'YYYYMM',
      startPlaceholder: '开始年月',
      endPlaceholder: '结束年月'
    },
    value: getPreviousMonthRange()
  },
  {
    field: 'abnorCateg',
    label: '异常类型',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择异常类型',
      props: {
        checkStrictly: false,
        emitPath: true,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: abnorCategEROptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  // {
  //   field: 'custCls',
  //   label: '客户分类',
  //   component: 'Select',
  //   componentProps: {
  //     placeholder: '请选择客户分类',
  //     options: custClsOptions,
  //     multiple: true,
  //     collapseTags: true,
  //     collapseTagsTooltip: true,
  //     clearable: true
  //   }
  // },
  {
    field: 'ecCateg',
    label: '用电类别',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择用电类别',
      props: {
        checkStrictly: false,
        emitPath: true,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: ecCategOptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  {
    field: 'deregAttrCls',
    label: '市场化属性分类',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择市场化属性分类',
      props: {
        checkStrictly: false,
        emitPath: false,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: deregAttrTypeOptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  }
])
const selectable = (row: TableRow) => {
  if (!row.abnorType || row.abnorType === '') {
    return true
  }
  return false
}
// 表格相关
const columns: TableColumn[] = [
  {
    field: '',
    type: 'selection', // 多选列
    width: 60,
    selectable: selectable
  },
  {
    field: 'index',
    type: 'index', // 序号列
    label: '序号',
    width: 60,
    fixed: 'left'
  },
  {
    field: 'mgtOrgName',
    label: '管理单位',
    width: 180,
    fixed: 'left'
  },
  {
    field: 'expYm',
    label: '量费年月',
    width: 120
  },
  {
    field: 'abnorType',
    label: '异常类别',
    width: 120
  },
  {
    field: 'abnorCateg',
    label: '异常类型',
    width: 120
  },
  {
    field: 'abnorDtlInfo',
    label: '异常说明',
    width: 200
  },
  {
    field: 'planNo',
    label: '计划编号',
    width: 180
  },
  {
    field: 'custNo',
    label: '用户编号',
    width: 180
  },
  {
    field: 'custName',
    label: '用户名称',
    minWidth: 210
  },
  {
    field: 'custClsName',
    label: '客户分类',
    width: 120
  },
  {
    field: 'deregAttrClsName',
    label: '市场化属性分类',
    width: 150
  },
  {
    field: 'action',
    label: '操作',
    width: 130,
    fixed: 'right',
    slots: {
      default: (data: any) => {
        // 使用h函数代替JSX语法
        return h(
          BaseButton,
          {
            type: 'primary',
            link: true,
            onClick: () => openDetailDialog(data.row)
          },
          '查看详情'
        )
      }
    }
  }
]

// 使用useTable hook进行表格数据管理
const { tableRegister, tableMethods, tableState } = useTable({
  immediate: false, // 不立即请求，而是在onMounted中手动请求
  fetchDataApi: async () => {
    try {
      // 获取搜索表单数据
      const formData = await getFormData()
      console.log('formData', formData)
      if (formData.ecCateg && formData.ecCateg.length !== 0) {
        formData.ecCateg = formData.ecCateg.flat()
      } else {
        formData.ecCateg = []
      }
      const requestParams = {
        startExpYm: formData.expYm?.[0],
        endExpYm: formData.expYm?.[1],
        abnorTypeList: formData.abnorCateg?.map((item) => item[0] || ''),
        abnorCategList:
          formData.abnorCateg?.length > 0 ? formData.abnorCateg?.map((item) => item[1] || '') : [], //
        deregAttrCls: formData.deregAttrCls, // 市场化属性分类
        // custCls: formData.custCls,
        ecCateg: formData.ecCateg,
        mgtOrgName: formData.mgtOrgName,
        pageSize: tableState.pageSize.value,
        pageNum: tableState.currentPage.value,
        custNo: formData.custNo
        // ...formData // 将查询条件合并到请求参数中
      }
      formData.abnorCateg?.map((item) => {
        if (item[0] == '全部') {
          requestParams.abnorTypeList = []
          requestParams.abnorCategList = []
        } else if (item[0] == '无异常') {
          requestParams.abnorCategList = []
        }
      })

      console.log('发送API请求参数:', JSON.stringify(requestParams))
      console.log('请求URL:', RECOGNITION_API.QUERY_INFO)

      // 发送请求
      const response = await queryQtyChargArchInfo(requestParams)
      console.log('API响应数据:', response)

      // 处理响应数据
      if (response) {
        // 检查响应数据结构并规范化数据格式，以适应useTable的需求
        let list: any[] = []
        let total = 0

        // 提取数据列表
        if (response.data) {
          // 如果存在data字段
          const responseData = response.data

          if (Array.isArray(responseData)) {
            // 如果data本身是数组
            list = responseData
            // 尝试从响应中获取total
            total = (response as any).total || responseData.length || 0
          } else if (typeof responseData === 'object') {
            // 如果data是对象
            if (responseData.list && Array.isArray(responseData.list)) {
              list = responseData.list
              total = responseData.total || responseData.list.length || 0
            } else if (responseData.records && Array.isArray(responseData.records)) {
              list = responseData.records
              total = responseData.total || responseData.records.length || 0
            } else if (responseData.data && Array.isArray(responseData.data)) {
              list = responseData.data
              total = responseData.total || responseData.data.length || 0
            } else if (responseData.rows && Array.isArray(responseData.rows)) {
              list = responseData.rows
              total = responseData.total || responseData.rows.length || 0
            } else {
              // 最后尝试将整个responseData作为单个记录
              list = [responseData]
              total = 1
            }

            // 如果上面没有找到total，尝试从其他常见字段中查找
            if (!total && typeof responseData.totalCount === 'number') {
              total = responseData.totalCount
            } else if (!total && typeof responseData.count === 'number') {
              total = responseData.count
            }
          }
        } else if (Array.isArray(response)) {
          // 如果响应本身就是数组
          list = response
          total = response.length
        } else if (typeof response === 'object') {
          // 直接从响应对象中查找数据
          const resp = response as any
          if (resp.list && Array.isArray(resp.list)) {
            list = resp.list
            total = resp.total || resp.list.length || 0
          } else if (resp.records && Array.isArray(resp.records)) {
            list = resp.records
            total = resp.total || resp.records.length || 0
          } else if (resp.data && Array.isArray(resp.data)) {
            list = resp.data
            total = resp.total || resp.data.length || 0
          } else if (resp.rows && Array.isArray(resp.rows)) {
            list = resp.rows
            total = resp.total || resp.rows.length || 0
          }

          // 尝试获取总数
          if (!total && typeof resp.totalCount === 'number') {
            total = resp.totalCount
          } else if (!total && typeof resp.count === 'number') {
            total = resp.count
          }
        }

        console.log('处理后的数据:', list.length, '条, 总数:', total)

        // 返回符合useTable要求的格式
        return {
          list,
          total
        }
      }

      return {
        list: [],
        total: 0
      }
    } catch (error: any) {
      console.error('获取数据失败:', error)
      ElMessage.error('获取数据失败: ' + (error instanceof Error ? error.message : '未知错误'))
      return {
        list: [],
        total: 0
      }
    }
  }
})

// 从useTable中解构获取数据和状态
const { loading, dataList, total, currentPage, pageSize } = tableState
const { refresh } = tableMethods

// 搜索处理
const handleSearch = async () => {
  // 使用await确保获取到表单数据
  const formData = await getFormData()
  console.log('搜索条件:', formData)

  // 重置页码到第一页
  currentPage.value = 1

  // 刷新数据
  refresh()
}

// 重置搜索
const handleReset = async () => {
  currentPage.value = 1
  refresh()
}

const { setProps } = tableMethods

// 在组件挂载后注册Search组件
onMounted(() => {
  // 注册搜索组件
  if (searchRef.value) {
    searchRegister(searchRef.value)

    // 统一设置所有表单项的大小和宽度
    schema.forEach((item) => {
      setSchema([
        {
          field: item.field,
          path: 'componentProps.size',
          value: 'default'
        },
        {
          field: item.field,
          path: 'componentProps.style',
          value: { width: '300px' }
        }
      ])
    })

    // 确保设置默认量费年月
    setValues({
      expYm: getPreviousMonthRange()
    })
  }
  // 设置固定表格高度 437.8
  setProps({
    height: 438
  })
  // 初始化表格数据
  refresh()
})

// 监听搜索条件变化
watch(
  () => getFormData(),
  () => {
    console.log('搜索条件已变更')
  },
  { deep: true }
)

// AI对话框状态
const aiDialogVisible = ref(false)
const aiInputData = ref({})
const isProcessingAI = ref(false) // 添加AI处理状态标志

// AI分析结果类型定义
interface AIAnalysisResult {
  summary?: string
  abnormalItems?: Array<{
    type: string
    description: string
    suggestion?: string
  }>
  statistics?: Record<string, number | string>
  [key: string]: any
}

// AI分析结果
const aiAnalysisResult = ref<AIAnalysisResult | null>([])
const aiResponseMessage = ref('')
const isSubmittingAnalysis = ref(false) // 提交状态
const submissionResult = ref<{ success: boolean; message: string } | null>(null) // 提交结果
const stopTaskID = ref('') // 分析回调task_id
const closeStatus = ref(false) // 弹窗关闭状态 false未执行 true已执行

// 处理异常识别（直接调用API而不显示对话框）
const openAIDialog = async () => {
  if (isProcessingAI.value) {
    ElMessage.warning('正在进行异常识别分析，请稍候...')
    return
  }

  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条需识别的数据！')
    return
  }

  try {
    isProcessingAI.value = true
    aiDialogVisible.value = true // 显示识别思路弹窗

    // 字段名中英文映射
    const fieldMapping = {
      // 基本信息
      mgtOrgName: '管理单位',
      expYm: '量费年月',
      abnorType: '异常类别',
      abnorCateg: '异常类型',
      abnorDtlInfo: '异常说明',
      planNo: '计划编号',
      custNo: '用户编号',
      custName: '用户名称',
      custClsName: '客户分类',
      deregAttrClsName: '市场化属性分类',

      // 算费信息
      bilgUnitNo: '核算包编号',
      thisMrQty: '本次抄见量',
      tSettleQty: '总结算量',
      tSettleExp: '总结算费',
      ctrtCap: '合同容量',
      runCap: '运行容量',
      ecCategName: '用电类别',
      indClsName: '行业分类',
      prcCode: '价格码',
      prcStTypeName: '定价策略类型',
      becCalcModeName: '基本电费计算方式',
      pfStdName: '功率因数考核标准',
      pfEvalModeName: '功率因数考核方式',
      voltage: '电压等级',

      // 计量点信息
      instStatName: '安装点状态',
      instNo: '安装点编号',
      instCap: '安装点容量',
      meterModeName: '计量方式',
      instUsageClsName: '安装点用途分类',
      eCalcModeCodeName: '能源计算方式',

      // 设备信息
      mrDevNo: '表计设备编号',
      devTypeName: '表计类型',
      lossNo: '损耗编号',
      lossAlgFlagName: '变损计算方式',
      adjDevNo: '调压设备编码',

      // 示数类型
      zxygReadType: '正向有功（总）',
      zxygjfReadType: '正向有功（尖峰）',
      zxygfReadType: '正向有功（峰）',
      zxyggReadType: '正向有功（谷）',
      zxygpReadType: '正向有功（平）',
      zxwgReadType: '正向无功（总）',
      wgReadType: '无功（Q4象限）',
      zdxlReadType: '最大需量',
      fxwgReadType: '反向无功（总）',
      fxygReadType: '反向有功（总）',

      // 其他可能的字段
      qtyChargArchInfoId: '记录ID',
      rectSug: '整改建议',
      rectStat: '整改状态'
    }

    // 字段名转换函数
    const convertFieldsToChinese = (data) => {
      const convertedData = {}
      for (const [key, value] of Object.entries(data)) {
        const chineseKey = fieldMapping[key] || key // 如果没有对应的中文名，保持原字段名
        convertedData[chineseKey] = value
      }
      return convertedData
    }

    // 准备传递给AI助手的结构化数据
    const structuredData = selectedRows.value.map((row) => {
      // 确保返回原始行的完整拷贝，不丢失任何字段
      const { abnorType, abnorCateg, abnorDtlInfo, ...restData } = { ...row }
      if (abnorType == '' || abnorType == null) {
        // 将英文字段名转换为中文字段名
        return convertFieldsToChinese(restData)
      }
    })

    // 构建要发送的消息
    const message = `请帮我分析以下电费数据是否存在异常，并以JSON格式返回分析结果：${JSON.stringify(structuredData)}`

    // 准备输入数据
    aiInputData.value = {
      table_data: JSON.stringify(structuredData)
    }

    // 配置API请求
    const config: DifyConfig = {
      apiKey: DIFY_API_KEY,
      apiBase: DIFY_API_V1_URL
    }

    // 创建请求对象
    const request: DifyRequest = {
      query: message,
      response_mode: 'streaming', // 使用流式处理模式
      user: 'user-20250515',
      inputs: aiInputData.value
    }

    // 消息内容累积
    let fullMessage = ''
    let extractedJson = null

    // 直接调用API
    await sendMessageToDify(
      request,
      config,
      (text, taskID) => {
        // 增量更新消息
        fullMessage += text
        isProcessingAI.value = false
        aiResponseMessage.value = fullMessage // 实时更新弹窗中显示的消息
        console.log('接收到消息片段', fullMessage)
        stopTaskID.value = taskID
        // 每次更新消息内容后滚动到底部
        nextTick(() => {
          scrollToBottom()
        })
      },
      (response) => {
        console.log('AI响应完成:', response)
        // 处理消息内容，提取JSON
        const processedContent = extractContentAndJson(fullMessage)

        // 如果有JSON数据，进行处理
        if (processedContent.jsonData) {
          console.log('提取到的JSON数据:', processedContent.jsonData)
          extractedJson = processedContent.jsonData
          aiAnalysisResult.value = processedContent.jsonData
          ElMessage.success('AI分析完成，已提取关键信息')
        } else {
          ElMessage.warning('AI分析完成，但未能提取到结构化数据')
        }

        // 模拟消息结束事件
        handleAiMessageEnd({
          message: processedContent.content,
          response: response,
          extractedJson: processedContent.jsonData
        })
        isProcessingAI.value = false
      },
      (error) => {
        console.error('AI分析出错:', error)
        ElMessage.error('AI分析出错: ' + (error.message || '未知错误'))
        isProcessingAI.value = false
        aiDialogVisible.value = false // 发生错误时关闭弹窗
      }
    )
  } catch (error) {
    console.error('异常识别处理出错:', error)
    ElMessage.error('异常识别处理出错，请重试')
    isProcessingAI.value = false
    aiDialogVisible.value = false // 发生错误时关闭弹窗
  }
}

// 识别结果弹窗关闭回调
const handleClose = async () => {
  closeStatus.value = true
  try {
    // 配置API请求
    const config: stopDifyConfig = {
      apiKey: DIFY_API_KEY,
      apiBase: DIFY_API_V1_URL,
      taskID: stopTaskID.value
    }

    // 创建请求对象
    const request: stopDifyRequest = {
      user: 'user-20250515'
    }

    // 直接调用API
    await stopMessageToDify(
      request,
      config,
      (response) => {
        console.log('获取请求结果:', response)
        // ElMessage.success('已停止当前任务')
        isProcessingAI.value = false
        aiDialogVisible.value = false // 关闭识别结果展示弹窗
        aiResponseMessage.value = '' // 重置结论内容
      },
      (error) => {
        console.error('停止执行报错:', error)
        ElMessage.error('停止执行报错: ' + (error.message || '未知错误'))
      }
    )
  } catch (error) {
    console.error('停止执行报错:', error)
    ElMessage.error('停止执行报错，请重试')
  }
}

// 处理提取的JSON数据
const extractContentAndJson = (text: string) => {
  const result = {
    content: text,
    jsonData: null as any
  }

  console.log('开始处理文本内容:', text)

  // 移除<think>标签内容
  result.content = text.replace(/<think>([\s\S]*?)<\/think>/g, '')

  // 尝试多种JSON提取模式
  const jsonPatterns = [
    // 模式1: ```json ... ``` 格式
    /```json\s*([\s\S]*?)\s*```/g,
    // 模式2: ``` ... ``` 格式（不带json标记）
    /```\s*([\s\S]*?)\s*```/g,
    // 模式3: 直接是JSON数组格式
    /\[\s*\{[\s\S]*?\}\s*\]/g
  ]

  let jsonArray: any[] = []
  let hasValidJson = false

  // 尝试每种模式
  for (const pattern of jsonPatterns) {
    const matches = [...result.content.matchAll(pattern)]
    if (matches.length > 0) {
      console.log(`使用模式 ${pattern} 找到 ${matches.length} 个匹配项`)

      for (const match of matches) {
        try {
          // 获取JSON文本并清理
          let jsonText = match[1] || match[0]
          jsonText = jsonText.trim()

          // 尝试解析JSON
          const parsed = JSON.parse(jsonText)

          // 处理解析结果
          if (Array.isArray(parsed)) {
            // 如果是数组，直接添加所有元素
            jsonArray = jsonArray.concat(parsed)
            console.log('成功解析JSON数组，长度:', parsed.length)
            hasValidJson = true
          } else if (typeof parsed === 'object') {
            // 如果是单个对象，添加到数组
            jsonArray.push(parsed)
            console.log('成功解析JSON对象')
            hasValidJson = true
          }
        } catch (err) {
          console.warn('JSON解析失败:', err, '原始文本:', jsonText)
          // 尝试修复常见的JSON格式问题
          try {
            // 1. 处理可能的单引号问题
            const fixedText = jsonText.replace(/'/g, '"')
            const parsed = JSON.parse(fixedText)
            if (Array.isArray(parsed)) {
              jsonArray = jsonArray.concat(parsed)
              hasValidJson = true
            } else {
              jsonArray.push(parsed)
              hasValidJson = true
            }
            console.log('修复单引号后成功解析JSON')
          } catch (fixErr) {
            console.warn('修复后仍然无法解析JSON:', fixErr)
          }
        }
      }

      // 如果找到有效的JSON，跳出循环
      if (hasValidJson) {
        break
      }
    }
  }

  // 如果没有找到有效的JSON数据，抛出错误
  if (!hasValidJson || jsonArray.length === 0) {
    throw new Error('未能提取到有效的JSON数据，请检查AI返回的格式是否正确')
  }

  // 设置结果
  try {
    // 确保所有对象都有必要的字段
    result.jsonData = jsonArray.map((item) => {
      // 验证必要字段
      if (!item.qtyChargArchInfoId) {
        throw new Error('JSON数据缺少必要字段: qtyChargArchInfoId')
      }

      return {
        qtyChargArchInfoId: item.qtyChargArchInfoId,
        abnormal_level1: {
          code: item.abnormal_level1?.code || '00',
          name: item.abnormal_level1?.name || item.abnorType || '无异常'
        },
        abnormal_level2: {
          code: item.abnormal_level2?.code || '0000',
          name: item.abnormal_level2?.name || item.abnorCateg || '无异常'
        },
        root_cause: item.root_cause || item.abnorDtlInfo || '无',
        rectSug: item.rectSug || '无'
      }
    })
    console.log('最终处理后的JSON数据:', result.jsonData)
  } catch (error) {
    throw new Error(`JSON数据格式验证失败: ${error.message}`)
  }

  // 清理内容中的多余空行
  result.content = result.content.replace(/\n{3,}/g, '\n\n').trim()

  return result
}

// 格式化消息内容（支持Markdown和高亮代码以及echarts图表）
const formatMessage = (message) => {
  if (!message) return ''

  let content = message
  console.log('message==========》', content)

  // 先移除code-block包装，因为markdown-it会处理```代码块
  content = content.replace(
    /<div class="code-block"><pre>([\s\S]*?)<\/pre><\/div>/g,
    '```\n$1\n```'
  )

  // 移除<think>标签内容
  content = content.replace(/<think>([\s\S]*?)<\/think>/g, '')

  // 移除<details>标签及其内容
  content = content.replace(/<details>[\s\S]*?<\/details>/g, '')

  // 移除JSON代码块，避免显示在界面上
  // content = content.replace(/```json\s*([\s\S]*?)\s*```/g, '')

  // 处理/files/tools路径，在前面添加域名前缀
  content = content.replace(/\/files\/tools/g, `${DIFY_API_BASE_URL}/files/tools`)

  try {
    // 使用markdown-it渲染
    return md.render(content)
  } catch (err) {
    console.error('Markdown渲染错误:', err)

    // 如果markdown渲染失败，回退到原始处理方式
    // 替换换行符为<br>
    return content.replace(/\n/g, '<br />')
  }
}

// 自动滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    try {
      // 找到消息内容容器
      const container = document.querySelector('.verification-dialog-content')
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    } catch (e) {
      console.error('滚动失败:', e)
    }
  }, 50)
}

// 处理AI对话中提取的JSON数据
const handleAiJsonExtracted = (jsonData) => {
  console.log('从AI对话中提取的JSON数据:', jsonData)
  aiAnalysisResult.value = jsonData
  // 这里可以立即处理JSON数据，例如更新UI、绘制图表等
  // 即使对话尚未结束也可以预先展示数据
}

// 处理AI对话结束事件
const handleAiMessageEnd = async (result) => {
  console.log('AI对话结束，结果:', result)
  aiResponseMessage.value = result.message
  isProcessingAI.value = false // 重置处理状态

  try {
    // 处理消息内容，提取JSON
    const processedContent = extractContentAndJson(result.message)

    // 如果有JSON数据，进行处理
    if (processedContent.jsonData) {
      console.log('提取到的JSON数据:', processedContent.jsonData)
      aiAnalysisResult.value = processedContent.jsonData
      ElMessage.success('AI分析完成，已提取关键信息')

      // 在对话结束时提交分析结果到后端
      await submitAnalysisToBackend()
    }
  } catch (error) {
    console.error('处理AI响应数据失败:', error)
    ElMessage.error(error.message || '处理AI响应数据失败')
    aiDialogVisible.value = false // 发生错误时关闭弹窗
    return // 停止后续代码执行
  }
}

// 转换JSON数据为变量并提交到后端
const submitAnalysisToBackend = async () => {
  if (!aiAnalysisResult.value) {
    ElMessage.warning('没有可提交的分析结果')
    return
  }

  try {
    isSubmittingAnalysis.value = true

    // 识别后的数据 - 确保是数组格式
    let afterRecognitionData = aiAnalysisResult.value

    // 如果是多层嵌套的数组，取第一个元素
    if (
      Array.isArray(afterRecognitionData) &&
      afterRecognitionData.length > 0 &&
      Array.isArray(afterRecognitionData[0])
    ) {
      afterRecognitionData = afterRecognitionData[0]
    }

    // 确保 afterRecognitionData 是数组
    if (!Array.isArray(afterRecognitionData)) {
      throw new Error('识别后的数据格式不正确，需要是数组格式')
    }

    console.log('识别后的数据:======》', afterRecognitionData)

    // 先映射数据
    const mappedData = afterRecognitionData.map((originalItem) => {
      const abnorCateg = originalItem.abnormal_level2?.name || originalItem.abnorCateg
      return {
        qtyChargArchInfoId: originalItem.qtyChargArchInfoId,
        // 将 abnormal_level1.name 赋值给 abnorType
        abnorType: originalItem.abnormal_level1?.name || originalItem.abnorType,
        // 将 abnormal_level2.name 赋值给 abnorCateg
        abnorCateg: originalItem.abnormal_level2?.name || originalItem.abnorCateg,
        // 将 root_cause 赋值给 abnorDtlInfo
        abnorDtlInfo: originalItem.root_cause || originalItem.abnorDtlInfo,
        rectSug: originalItem.rectSug || originalItem.rectSug,
        rectStat: abnorCateg === '无异常' ? '10' : '01'
      }
    })

    // 合并具有相同 qtyChargArchInfoId abnorType 的数据
    const mergedDataMap = new Map()

    mappedData.forEach((item) => {
      const key = `${item.qtyChargArchInfoId}_${item.abnorType}`

      if (mergedDataMap.has(key)) {
        const existingItem = mergedDataMap.get(key)
        // 只有当abnorType不是"无异常"时才合并字段
        if (item.abnorType !== '无异常') {
          existingItem.abnorCateg = [existingItem.abnorCateg, item.abnorCateg]
            .filter(Boolean)
            .join(';')
          existingItem.abnorDtlInfo = [existingItem.abnorDtlInfo, item.abnorDtlInfo]
            .filter(Boolean)
            .join(';')
          existingItem.rectSug = [existingItem.rectSug, item.rectSug].filter(Boolean).join(';')
        }
      } else {
        mergedDataMap.set(key, { ...item })
      }
    })

    // 转换回数组
    const submissionData = Array.from(mergedDataMap.values())

    console.log('提交处理后的分析结果到后端的数据:======》', submissionData)
    // 调用异常识别API
    const res = await addAbnormalRecognition(submissionData)
    if (res && (res as IResponse<any>).code === 200) {
      ElMessage.success('提交成功')
      refresh()
    } else {
      ElMessage.error('提交失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    isSubmittingAnalysis.value = false
  }
}

// 创建markdown-it实例
const md = new MarkdownIt({
  html: true, // 禁用HTML标签
  breaks: true, // 转换'\n'为<br>
  linkify: true, // 自动识别URL并转换为链接
  typographer: true, // 启用一些语言中性的替换和引号美化
  highlight: function (code, lang) {
    return `<pre class="language-${lang}"><code>${code}</code></pre>`
  }
})
// 详情弹窗相关
const detailDialogVisible = ref(false)
const currentDetail = ref<any>(null)

// 打开详情弹窗
const openDetailDialog = (row: any) => {
  // 模拟获取更多详细数据
  currentDetail.value = {
    ...row
  }
  detailDialogVisible.value = true
}

// 关闭详情弹窗
const closeDetailDialog = () => {
  detailDialogVisible.value = false
}

// 导入数据弹窗相关
const importDialogVisible = ref(false)
const importing = ref(false)
const selectedFile = ref<File | null>(null)

// 打开导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true
  selectedFile.value = null
}

// 文件变更处理
const handleFileChange = (file: any) => {
  const isExcel =
    file.raw.type === 'application/vnd.ms-excel' ||
    file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件！')
    return false
  }

  selectedFile.value = file.raw
  return true
}

// 文件移除处理
const handleFileRemove = () => {
  selectedFile.value = null
}

// 导入处理
const handleImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }

  importing.value = true

  try {
    // 创建FormData
    const formData = new FormData()
    formData.append('file', selectedFile.value)

    // 调用API上传
    const res = await importData(formData)
    console.log('导入响应:', res)

    // 处理响应
    if (res && res.success == true) {
      ElMessage.success(`成功导入数据`)
      importDialogVisible.value = false

      // 重新加载数据
      refresh()
    } else {
      ElMessage.error(res?.data?.msg || res?.data?.message || '导入失败，请检查文件格式是否正确')
    }
  } catch (error) {
    console.error('导入处理出错:', error)
    ElMessage.error('导入处理出错，请重试')
  } finally {
    importing.value = false
  }
}

// 下载模板
const downloadTemplate = async (event: Event) => {
  event.preventDefault()
  event.stopPropagation()

  try {
    ElMessage.info('正在下载模板...')

    // 调用下载API
    const res = await downloadTemplateApi()

    // 处理二进制数据
    const blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })

    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = '电费数据导入模板.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('模板下载失败:', error)
    ElMessage.error('模板下载失败，请重试')
  }
}

// 初始化确认弹窗
const openInitConfirmDialog = () => {
  ElMessageBox.confirm('是否确认初始化？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      handleInit()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '初始化已取消'
      })
    })
}
const ELECTRICITY_API_URL = import.meta.env.VITE_ELECTRICITY_API_URL
// 初始化功能实现
const handleInit = async () => {
  try {
    // 提示用户正在初始化
    ElMessage({
      message: '正在初始化系统，请稍候...',
      type: 'info',
      duration: 2000
    })
    // 获取搜索表单数据
    const formData = await getFormData()
    console.log('formData', formData)
    if (formData.ecCateg && formData.ecCateg.length !== 0) {
      formData.ecCateg = formData.ecCateg.flat()
    } else {
      formData.ecCateg = []
    }
    const requestParams = {
      startExpYm: formData.expYm?.[0],
      endExpYm: formData.expYm?.[1],
      abnorTypeList: formData.abnorCateg?.map((item) => item[0] || ''),
      abnorCategList:
        formData.abnorCateg?.length > 0 ? formData.abnorCateg?.map((item) => item[1] || '') : [], //
      deregAttrCls: formData.deregAttrCls, // 市场化属性分类
      // custCls: formData.custCls,
      ecCateg: formData.ecCateg,
      mgtOrgName: formData.mgtOrgName,
      custNo: formData.custNo
      // ...formData // 将查询条件合并到请求参数中
    }
    formData.abnorCateg?.map((item) => {
      if (item[0] == '全部') {
        requestParams.abnorTypeList = []
        requestParams.abnorCategList = []
      } else if (item[0] == '无异常') {
        requestParams.abnorCategList = []
      }
    })

    console.log('发送API请求参数:', JSON.stringify(requestParams))

    // 2. 调用初始化接口
    const response = await axios.post(`${ELECTRICITY_API_URL}/api/users/deleteQtyChargArchInfo`, {
      ...requestParams
    })

    // 3. 判断接口返回状态
    if (response.status === 200 && response.data) {
      refresh()
      ElMessage({
        message: '初始化成功!',
        type: 'success',
        duration: 2000
      })

      // 4. 接口返回成功后跳转到数据导入页面
      setTimeout(() => {
        // 跳转到数据导入页面electricityAbnormal/import
        router.push('/electricityAbnormal/import')
      }, 3000)
    } else {
      ElMessage.error('初始化失败，请重试')
    }
  } catch (error) {
    console.error('初始化过程出错:', error)
    ElMessage.error('初始化过程出错: ' + (error instanceof Error ? error.message : '未知错误'))
  }
}

// 重置按钮的可见性
const resetButtonVisible = ref(true)

// 整改状态映射
const rectStatMap = {
  '00': '未处理',
  '01': '未处理',
  '02': '处理中',
  '03': '已处理',
  '04': '无需处理',
  '10': '无异常'
}

// 获取整改状态名称
const getRectStatName = (code: string) => {
  return rectStatMap[code] || '未知状态'
}

// 关闭AI对话框
const closeAiDialog = () => {
  aiDialogVisible.value = false // 关闭识别结果展示弹窗
  aiResponseMessage.value = ''
}

// 表格样式，奇行背景色#f6f6f6偶行背景色#ffffff
const tableRowStyle = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? { background: '#ffffff' } : { background: '#fcfcfc' }
}
</script>

<template>
  <ContentWrap title="电费异常识别" message="对站点电费进行异常识别和处理">
    <CustomSearch
      :schema="schema"
      :layout="'bottom'"
      :button-position="'right'"
      :custom-buttons="[
        {
          label: '导入数据',
          type: 'success',
          plain: true,
          icon: 'vi-ep:upload-filled',
          color: '#286af6',
          onClick: showImportDialog
        },
        {
          label: '异常识别',
          type: 'success',
          icon: 'vi-ep:chat-dot-square',
          loading: isProcessingAI,
          color: '#286af6',
          onClick: openAIDialog
        },
        {
          label: '初始化',
          type: 'primary',
          icon: 'vi-ep:refresh',
          color: '#ff6b35',
          onClick: openInitConfirmDialog
        }
      ]"
      @search="handleSearch"
      @reset="handleReset"
      ref="searchRef"
    />
    <div>总计：{{ total }}条数据</div>
    <div class="table-container">
      <Table
        ref="tableRef"
        v-model:pageSize="pageSize"
        v-model:currentPage="currentPage"
        :columns="columns"
        :data="dataList"
        :fit="true"
        row-key=""
        :loading="loading"
        :pagination="{
          total,
          pageSize,
          currentPage,
          pageSizes: [10, 20, 50, 100],
          background: true
        }"
        height="238.8"
        style="
          width: 100%;
          --el-table-border-color: #cdd7d5;
          --el-table-text-color: #171717;
          --el-table-header-text-color: #585858;
        }"
        :header-cell-style="{
          background: '#e5f5f3', // 背景色
          color: '#585858' // 文字颜色
        }"
        :rowStyle="tableRowStyle"
        @register="tableRegister"
        @refresh="refresh"
        @selection-change="handleSelectionChange"
      />
    </div>
    <!-- 导入数据弹窗 -->
    <ElDialog v-model="importDialogVisible" title="导入数据" width="500px" destroy-on-close>
      <div class="import-dialog-content">
        <ElUpload
          class="upload-wrapper"
          drag
          action="#"
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          accept=".xls,.xlsx"
        >
          <ElIcon class="upload-icon">
            <Icon icon="vi-ep:upload-filled" />
          </ElIcon>
          <div class="upload-text">
            <span>将文件拖到此处，或<em>点击上传</em></span>
            <div class="upload-tip">支持 .xls, .xlsx 格式文件</div>
          </div>
        </ElUpload>

        <div class="import-actions">
          <a href="#" @click="downloadTemplate" class="template-link">
            <Icon icon="vi-ep:download" class="mr-5px" />
            下载导入模板
          </a>
          <div class="action-buttons">
            <ElButton @click="importDialogVisible = false">取 消</ElButton>
            <ElButton type="primary" @click="handleImport" :loading="importing"> 导 入 </ElButton>
          </div>
        </div>
      </div>
    </ElDialog>

    <!-- 不要AI分析结果显示区域，在有分析结果时显示 -->

    <!-- 详情弹窗 -->
    <ElDialog
      v-model="detailDialogVisible"
      title="详情"
      width="70%"
      :before-close="closeDetailDialog"
      destroy-on-close
      class="detail-dialog"
      style=""
    >
      <div class="detail-container">
        <div class="detail-section">
          <div class="detail-title">异常信息</div>
          <div class="detail-info">
            <div class="detail-item">
              <div class="detail-label">异常类别：</div>
              <div class="detail-value">{{ currentDetail?.abnorType }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">异常类型：</div>
              <div class="detail-value">{{ currentDetail?.abnorCateg }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">异常说明：</div>
              <div class="detail-value">{{ currentDetail?.abnorDtlInfo }}</div>
            </div>
          </div>
        </div>
        <div class="detail-section">
          <div class="detail-title">算费信息</div>
          <div class="detail-info">
            <div class="detail-item">
              <div class="detail-label">量费年月：</div>
              <div class="detail-value">{{ currentDetail?.expYm }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">计划编号：</div>
              <div class="detail-value">{{ currentDetail?.planNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">核算包编号：</div>
              <div class="detail-value">{{ currentDetail?.bilgUnitNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">本次抄见量：</div>
              <div class="detail-value">{{ currentDetail?.thisMrQty }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">总结算量：</div>
              <div class="detail-value">{{ currentDetail?.tSettleQty }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">总结算费：</div>
              <div class="detail-value">{{ currentDetail?.tSettleExp }}</div>
            </div>
          </div>
        </div>
        <div class="detail-section">
          <div class="detail-title">本次抄见量</div>
          <div class="reading-table-container">
            <table class="reading-table">
              <thead>
                <tr>
                  <td class="table-label">示数类型</td>
                  <td v-if="currentDetail?.zxygReadType" class="table-header">正向有功（总）</td>
                  <td v-if="currentDetail?.zxygjfReadType" class="table-header"
                    >正向有功（尖峰）</td
                  >
                  <td v-if="currentDetail?.zxygfReadType" class="table-header">正向有功（峰）</td>
                  <td v-if="currentDetail?.zxyggReadType" class="table-header">正向有功（谷）</td>
                  <td v-if="currentDetail?.zxygpReadType" class="table-header">正向有功（平）</td>
                  <td v-if="currentDetail?.zxwgReadType" class="table-header">正向无功（总）</td>
                  <td v-if="currentDetail?.wgReadType" class="table-header">无功（Q4象限）</td>
                  <td v-if="currentDetail?.zdxlReadType" class="table-header">最大需量</td>
                  <td v-if="currentDetail?.fxwgReadType" class="table-header">反向无功（总）</td>
                  <td v-if="currentDetail?.fxygReadType" class="table-header">反向有功（总）</td>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td class="table-label">抄见电量</td>
                  <td v-if="currentDetail?.zxygReadType" class="table-cell">{{
                    currentDetail?.zxygReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zxygjfReadType" class="table-cell">{{
                    currentDetail?.zxygjfReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zxygfReadType" class="table-cell">{{
                    currentDetail?.zxygfReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zxyggReadType" class="table-cell">{{
                    currentDetail?.zxyggReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zxygpReadType" class="table-cell">{{
                    currentDetail?.zxygpReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zxwgReadType" class="table-cell">{{
                    currentDetail?.zxwgReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.wgReadType" class="table-cell">{{
                    currentDetail?.wgReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zdxlReadType" class="table-cell">{{
                    currentDetail?.zdxlReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.fxwgReadType" class="table-cell">{{
                    currentDetail?.fxwgReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.fxygReadType" class="table-cell">{{
                    currentDetail?.fxygReadTypeNameDl || '-'
                  }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="detail-section">
          <div class="detail-title">基础档案信息</div>
          <div class="detail-info">
            <div class="detail-item">
              <div class="detail-label">管理单位：</div>
              <div class="detail-value">{{ currentDetail?.mgtOrgName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">用户编号：</div>
              <div class="detail-value">{{ currentDetail?.custNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">用户名称：</div>
              <div class="detail-value">{{ currentDetail?.custName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">客户分类：</div>
              <div class="detail-value">{{ currentDetail?.custClsName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">市场化属性分类：</div>
              <div class="detail-value">{{ currentDetail?.deregAttrClsName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">合同容量：</div>
              <div class="detail-value">{{ currentDetail?.ctrtCap }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">运行容量：</div>
              <div class="detail-value">{{ currentDetail?.runCap }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">用电类别：</div>
              <div class="detail-value">{{ currentDetail?.ecCategName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">行业分类：</div>
              <div class="detail-value">{{ currentDetail?.indClsName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">价格码：</div>
              <div class="detail-value">{{ currentDetail?.prcCode }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">定价策略类型：</div>
              <div class="detail-value">{{ currentDetail?.prcStTypeName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">基本电费计算方式：</div>
              <div class="detail-value">{{ currentDetail?.becCalcModeName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">功率因数考核标准：</div>
              <div class="detail-value">{{ currentDetail?.pfStdName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">功率因数考核方式：</div>
              <div class="detail-value">{{ currentDetail?.pfEvalModeName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">电压等级：</div>
              <div class="detail-value">{{ currentDetail?.voltage }}</div>
            </div>
          </div>
        </div>
        <div class="detail-section">
          <div class="detail-title">计量点信息</div>
          <div class="detail-info">
            <div class="detail-item">
              <div class="detail-label">安装点状态：</div>
              <div class="detail-value">{{ currentDetail?.instStatName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">安装点编号：</div>
              <div class="detail-value">{{ currentDetail?.instNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">安装点容量：</div>
              <div class="detail-value">{{ currentDetail?.instCap }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">计量方式：</div>
              <div class="detail-value">{{ currentDetail?.meterModeName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">安装点用途分类：</div>
              <div class="detail-value">{{ currentDetail?.instUsageClsName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">能源计算方式：</div>
              <div class="detail-value">{{ currentDetail?.eCalcModeCodeName }}</div>
            </div>
          </div>
        </div>
        <div class="detail-section-end">
          <div class="detail-title">设备信息</div>
          <div class="detail-info">
            <div class="detail-item">
              <div class="detail-label">表计设备编号：</div>
              <div class="detail-value">{{ currentDetail?.mrDevNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">表计类型：</div>
              <div class="detail-value">{{ currentDetail?.devTypeName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">损耗编号：</div>
              <div class="detail-value">{{ currentDetail?.lossNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">变损计算方式：</div>
              <div class="detail-value">{{ currentDetail?.lossAlgFlagName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">调压设备编码：</div>
              <div class="detail-value">{{ currentDetail?.adjDevNo }}</div>
            </div>
          </div>
        </div>
      </div>
    </ElDialog>
  </ContentWrap>
  <!-- 识别结果展示弹窗 -->
  <ElDialog
    v-model="aiDialogVisible"
    title="识别结果"
    width="700px"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    class="verification-dialog"
    :before-close="handleClose"
  >
    <div class="verification-dialog-content">
      <!-- 加载中状态 -->
      <div v-if="isProcessingAI" class="loading-container">
        <div class="loading-icon">
          <Icon icon="vi-ep:loading" :size="40" class="is-loading" />
        </div>
        <div class="loading-text">
          <p>正在进行电费异常识别，请稍候...</p>
        </div>
      </div>

      <!-- 识别思路展示 -->
      <div v-else class="message-content">
        <div class="message-text markdown-body" v-html="formatMessage(aiResponseMessage)"></div>
      </div>

      <!-- <div v-else class="suggestion-section" v-html="formatMessage(aiResponseMessage)"> </div> -->
    </div>

    <template #footer>
      <div class="dialog-footer">
        <ElButton v-if="!isProcessingAI" type="primary" @click="handleClose"> 确 认 </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<style scoped>
.ml-2 {
  margin-left: 8px;
}

.mb-10px {
  margin-bottom: 10px;
}

.search-container {
  display: flex;
  align-items: flex-end;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.search-buttons {
  margin-left: 16px;
  margin-bottom: 16px;
}

.table-operations {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.operation-button {
  margin-left: 8px;
}

.table-container {
  margin-top: 10px;
  width: 100%;
  overflow-x: auto;
}

.view-detail-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: none;
}

.view-detail-link:hover {
  text-decoration: underline;
}

/* 适配移动端 */
@media (max-width: 768px) {
  .table-operations {
    flex-direction: column;
    align-items: flex-start;
  }

  .operation-button {
    margin-left: 0;
    margin-top: 8px;
  }

  .search-buttons {
    margin-left: 0;
    margin-top: 8px;
  }

  /* 移动端悬浮按钮位置调整 */
  .floating-button {
    right: 10px;
    bottom: 60px;
  }
}

.detail-dialog :deep(.el-dialog__header) {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

.detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

/* 添加导入弹窗相关样式 */
.import-dialog-content {
  padding: 20px;
}

.upload-wrapper {
  width: 100%;
  margin-bottom: 20px;
}

.upload-icon {
  font-size: 40px;
  color: #409eff;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.upload-text em {
  color: #409eff;
  font-style: normal;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.import-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.template-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.template-link:hover {
  color: #66b1ff;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

/* 添加AI分析结果区域样式 */
.analysis-result-container {
  margin-top: 20px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #eaeaea;
}

.analysis-result-container h3 {
  margin-top: 0;
  color: #303133;
  font-size: 18px;
  border-bottom: 1px solid #dcdfe6;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.result-section {
  margin-bottom: 20px;
}

.result-section h4 {
  font-size: 16px;
  color: #606266;
  margin-bottom: 12px;
}

.statistics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.stat-item {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.stat-label {
  color: #909399;
  font-size: 13px;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  color: #303133;
  font-weight: bold;
}

.abnormal-item {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 10px;
}

.abnormal-type {
  font-weight: bold;
  color: #f56c6c;
  margin-bottom: 8px;
}

.abnormal-description {
  margin-bottom: 8px;
  line-height: 1.5;
}

.abnormal-suggestion {
  color: #67c23a;
  font-style: italic;
  border-left: 3px solid #67c23a;
  padding-left: 10px;
  margin-top: 8px;
}

/* 详情弹窗样式 */
.detail-container {
  width: 100%;
  max-height: 70vh;
  overflow-y: auto;
  background-color: #f2f2f2;
  padding: 26px 6px 26px 26px;
}

.detail-section {
  padding: 6px;
  border-bottom: 1px solid #999;
}

.detail-section-end {
  padding: 6px;
}

.detail-title {
  font-size: 18px;
  font-weight: bold;
  margin-top: 4px;
  margin-bottom: 6px;
}

.detail-info {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 0 0 0 70px;
}

.detail-item {
  width: 33.333%;
  min-height: 30px;
  display: flex;
  padding: 10px;
}

.detail-label {
  font-weight: bold;
  color: #606266;
  /* min-width: 130px; */
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #303133;
  word-break: break-all;
}

/* 识别思路展示弹窗样式 */
.verification-dialog-content {
  height: 500px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 500px;
}

.loading-icon,
.result-icon {
  margin-bottom: 20px;
  color: #e6a23c;
}

/* .is-loading {
  animation: rotate 2s linear infinite;
} */

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.loading-text,
.result-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.suggestion-section {
  text-align: left;
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
  width: 100%;
  height: 500px;
  overflow-y: auto;
  white-space: pre-wrap;
  font-size: 14px;
  line-height: 1.5;
}

.message-content {
  margin-left: 10px;
  padding: 12px 16px;
  max-width: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  :deep(.markdown-body) {
    line-height: 1.6;
    word-break: break-word;

    /* Markdown 样式 */
    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
      margin-top: 24px;
      margin-bottom: 16px;
      font-weight: 600;
      line-height: 1.25;
    }

    h1 {
      font-size: 2em;
      margin-top: 0;
    }

    h2 {
      font-size: 1.5em;
    }

    h3 {
      font-size: 1.25em;
    }

    h4 {
      font-size: 1em;
    }

    p {
      margin-top: 0;
      margin-bottom: 10px;
    }

    a {
      color: #0366d6;
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }

    code {
      font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
      background-color: rgba(27, 31, 35, 0.05);
      padding: 0.2em 0.4em;
      border-radius: 3px;
      font-size: 85%;
    }

    pre {
      background-color: #1e1e1e;
      border-radius: 6px;
      padding: 16px;
      overflow: auto;
      margin: 16px 0;

      code {
        background-color: transparent;
        padding: 0;
        white-space: pre;
        font-size: 85%;
        color: #e0e0e0;
      }
    }

    blockquote {
      padding: 0 1em;
      color: #6a737d;
      border-left: 0.25em solid #dfe2e5;
      margin: 0 0 16px 0;
    }

    ul,
    ol {
      padding-left: 2em;
      margin-top: 0;
      margin-bottom: 16px;
    }

    table {
      display: block;
      width: 100%;
      overflow: auto;
      margin-top: 0;
      margin-bottom: 16px;
      border-collapse: collapse;

      th,
      td {
        padding: 6px 13px;
        border: 1px solid #dfe2e5;
      }

      th {
        font-weight: 600;
        background-color: #f6f8fa;
      }

      tr:nth-child(2n) {
        background-color: #f6f8fa;
      }
    }

    img {
      max-width: 100%;
      box-sizing: content-box;
    }

    hr {
      height: 0.25em;
      padding: 0;
      margin: 24px 0;
      background-color: #e1e4e8;
      border: 0;
    }

    .echarts-container {
      margin: 16px 0;
      border: 1px solid #eaeaea;
      border-radius: 6px;
    }
  }

  :deep(.code-block) {
    margin: 12px 0;
    background-color: #1e1e1e;
    border-radius: 6px;
    overflow: hidden;

    pre {
      padding: 12px;
      margin: 0;
      font-family: 'Courier New', Courier, monospace;
      white-space: pre-wrap;
      color: #e0e0e0;
    }
  }
}

.message-text {
  word-break: break-word;
  /* white-space: pre-wrap; */
  line-height: 1.6;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 示数类型表格样式 */
.reading-table-container {
  padding: 0 0 0 70px;
  margin-top: 10px;
}

.reading-table {
  width: 100%;
  border-collapse: collapse;
  /* background-color: #fff; */
  border: 1px solid #dcdfe6;
  font-size: 14px;
}

.reading-table thead {
  /* background-color: #f5f7fa; */
}

.reading-table .table-label {
  /* background-color: #e6f7ff; */
  font-weight: bold;
  color: #303133;
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  min-width: 80px;
}

.reading-table .table-header {
  /* background-color: #f5f7fa; */
  font-weight: bold;
  color: #606266;
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  font-size: 13px;
  white-space: nowrap;
}

.reading-table .table-cell {
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  color: #303133;
  white-space: nowrap;
}
</style>
